package com.gxnu.edu.cn.ttxxt.controller;

import com.gxnu.edu.cn.ttxxt.entity.Notifications;
import com.gxnu.edu.cn.ttxxt.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpStatusCodeException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/api/notifications")
public class NotificationController {

    @Autowired
    private NotificationService notificationService;

    @GetMapping("/user/{userId}")
    public ResponseEntity<?> getNotifications(@PathVariable Long userId) {
        List<Notifications> notifications = notificationService.getNotifications(userId);
        return ResponseEntity.ok(notifications);
    }

    @GetMapping("/user/friend/{userId}")
    public ResponseEntity<?> getNotificationsFrendApple(@PathVariable Long userId) {
        List<Notifications> notifications = notificationService.getNotificationsFrendApple(userId);
        return ResponseEntity.ok(notifications);
    }

    @GetMapping("/user/{userId}/unread")
    public ResponseEntity<?> getUnreadNotifications(@PathVariable Long userId) {
        List<Notifications> notifications = notificationService.getUnreadNotifications(userId);
        return ResponseEntity.ok(notifications);
    }

    @PostMapping("/{notificationId}/read")
    public ResponseEntity<?> markNotificationAsRead(@PathVariable Long notificationId) {
        notificationService.markNotificationAsRead(notificationId);
        return ResponseEntity.ok("通知已标记为已读");
    }

    @PostMapping("/user/{userId}/read-all")
    public ResponseEntity<?> markAllNotificationsAsRead(@PathVariable Long userId) {
        notificationService.markAllNotificationsAsRead(userId);
        return ResponseEntity.ok("所有通知已标记为已读");
    }

    @PostMapping("/{notificationId}/process")
    public ResponseEntity<Map<String, Object>> processNotification(
            @PathVariable Long notificationId,
            @RequestBody Map<String, Integer> request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 1. 参数校验
            Integer status = request.get("status");
            if (status == null) {
                result.put("code", 400);
                result.put("message", "缺少必要参数 status");
                return ResponseEntity.badRequest().body(result);
            }

            // 2. 调用业务方法并获取处理结果
            String processResult = notificationService.processNotification(notificationId, status);

            // 3. 处理业务方法返回的特殊状态（如果有）
            if ("NOTIFICATION_NOT_FOUND".equals(processResult)) {
                result.put("code", 404);
                result.put("message", "通知不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            } else if ("INVALID_STATUS".equals(processResult)) {
                result.put("code", 400);
                result.put("message", "状态值不合法，仅支持 2（同意）或 3（拒绝）");
                return ResponseEntity.badRequest().body(result);
            }

            // 4. 正常返回
            result.put("code", 200);
            result.put("status", "success");
            result.put("message", "通知已处理");
            return ResponseEntity.ok(result);

        } catch (HttpMessageNotReadableException e) {
            // 处理 JSON 解析异常（客户端请求格式错误）
            result.put("code", 400);
            result.put("message", "请求体格式错误：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);

        } catch (HttpStatusCodeException e) {
            // 处理 HTTP 状态码异常（如调用其他服务失败）
            result.put("code", e.getStatusCode().value());
            result.put("message", "调用服务失败：" + e.getResponseBodyAsString());
            return ResponseEntity.status(e.getStatusCode()).body(result);

        } catch (Exception e) {
            // 兜底捕获其他异常（数据库错误、空指针等）
            result.put("code", 500);
            result.put("message", "服务器内部错误：" + e.getMessage());
            // 生产环境建议记录日志而非直接返回堆栈信息
            // logger.error("处理通知失败", e);
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @PostMapping("/{notificationId}/reject")
    public ResponseEntity<Map<String, Object>> rejectFriendRequest(
            @PathVariable Long notificationId,
            @RequestBody Map<String, Integer> request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 1. 参数校验
            Integer status = request.get("status");
            if (status == null) {
                result.put("code", 400);
                result.put("message", "缺少必要参数 status");
                return ResponseEntity.badRequest().body(result);
            }

            // 2. 调用业务方法并获取处理结果
            String processResult = notificationService.rejectNotification(notificationId, status);

            // 3. 处理业务方法返回的特殊状态（如果有）
            if ("NOTIFICATION_NOT_FOUND".equals(processResult)) {
                result.put("code", 404);
                result.put("message", "通知不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            } else if ("INVALID_STATUS".equals(processResult)) {
                result.put("code", 400);
                result.put("message", "状态值不合法，仅支持 2（同意）或 3（拒绝）");
                return ResponseEntity.badRequest().body(result);
            }

            // 4. 正常返回
            result.put("code", 200);
            result.put("status", "success");
            result.put("message", "通知已处理");
            return ResponseEntity.ok(result);

        } catch (HttpMessageNotReadableException e) {
            // 处理 JSON 解析异常（客户端请求格式错误）
            result.put("code", 400);
            result.put("message", "请求体格式错误：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);

        } catch (HttpStatusCodeException e) {
            // 处理 HTTP 状态码异常（如调用其他服务失败）
            result.put("code", e.getStatusCode().value());
            result.put("message", "调用服务失败：" + e.getResponseBodyAsString());
            return ResponseEntity.status(e.getStatusCode()).body(result);

        } catch (Exception e) {
            // 兜底捕获其他异常（数据库错误、空指针等）
            result.put("code", 500);
            result.put("message", "服务器内部错误：" + e.getMessage());
            // 生产环境建议记录日志而非直接返回堆栈信息
            // logger.error("处理通知失败", e);
            return ResponseEntity.internalServerError().body(result);
        }
    }
}
    